package com.uzai.console.service.alipaymch.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AccDetailModel;
import com.alipay.api.domain.AccPayeeInfo;
import com.alipay.api.request.AlipayTradeCloseRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.*;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.dto.alipaymchbatch.AlipayBatchPayDto;
import com.uzai.console.dto.alipaymchbatch.AlipayMchBatchDetailQuery;
import com.uzai.console.entity.*;
import com.uzai.console.enums.AlipayMchBatchDetailStatusEnum;
import com.uzai.console.enums.AlipayStatusEnum;
import com.uzai.console.mapper.AlipayMchAuthMapper;
import com.uzai.console.mapper.AlipayMchBatchDetailMapper;
import com.uzai.console.mapper.AlipayMchBatchMapper;
import com.uzai.console.service.alipaymch.AlipayFundBatchService;
import com.uzai.console.service.alipaymch.AlipayMchBatchPayService;
import com.uzai.console.service.takebal.UserTakeBalService;
import com.uzai.console.vo.alipaydetail.AlipayTradeQueryVo;
import com.uzai.console.vo.alipaymchbatch.AlipayMchBatchTransVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Auther: jianghan
 * @Date: 2021/12/15 19:08
 * @Description:
 */
@Service
public class AlipayMchBatchPayServiceImpl implements AlipayMchBatchPayService {

    private static Logger logger = LoggerFactory.getLogger(AlipayMchBatchPayServiceImpl.class);

    @Autowired
    private AlipayMchAuthMapper alipayMchAuthMapper;
    @Autowired
    private AlipayFundBatchService alipayFundBatchService;
    @Autowired
    private AlipayMchBatchMapper alipayMchBatchMapper;
    @Autowired
    private AlipayMchBatchDetailMapper alipayMchBatchDetailMapper;
    @Autowired
    private UserTakeBalService userTakeBalService;

    @Override
    public AlipayMchBatchTransVo batchPayCreate(AlipayBatchPayDto alipayBatchPayDto, AlipayMchAuth alipayMchAuth) {
        logger.info(JSONObject.toJSONString(alipayBatchPayDto));

        if (alipayMchAuth==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "支付宝授权不存在");
        }

        // 创建单号
        AlipayFundBatchCreateResponse createResponse = alipayFundBatchService.create(alipayMchAuth.getAppAuthToken(), alipayBatchPayDto);
        if (StringUtils.isBlank(createResponse.getBatchTransId())){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION,"创建支付失败："+createResponse.getSubMsg());
        }

        // 生成支付链接
        AlipayFundTransPagePayResponse payResponse = alipayFundBatchService.pay(alipayMchAuth.getAppAuthToken(), createResponse.getBatchTransId());
        if (StringUtils.isBlank(payResponse.getBody())){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION,"创建支付失败：" + payResponse.getSubMsg());
        }

        AlipayMchBatchTransVo alipayMchBatchTransVo = new AlipayMchBatchTransVo();
        alipayMchBatchTransVo.setPayUrl(payResponse.getBody());
        alipayMchBatchTransVo.setBatchTransId(createResponse.getBatchTransId());
        alipayMchBatchTransVo.setBatchNo(alipayBatchPayDto.getBatchNo());
        return alipayMchBatchTransVo;
    }

    @Override
    public Object batchPayQuery(AlipayMchAuth alipayMchAuth, AlipayMchBatch alipayMchBatch) {
        logger.info("appId:{},batchNo:{}", new Object[]{alipayMchAuth, alipayMchBatch});
        // 获取授权
        if (alipayMchAuth == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION,"支付宝授权不存在");
        }
        if (alipayMchBatch == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "转账批次号不存在");
        }

        AlipayFundBatchDetailQueryResponse queryResponse = alipayFundBatchService.query(alipayMchBatch.getOutBatchNo(), alipayMchAuth.getAppAuthToken());

        if (queryResponse==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "查询失败");
        }

        return queryResponse;
    }

    /**
     * 在线查询支付宝个人批量转账支付结果
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param id
     * @return null
     */
    @Transactional
    public void alipayMchBatchQuery(Long id){
        try{

            //查询支付宝批量支付交易记录
            AlipayMchBatch alipayMchBatch = alipayMchBatchMapper.selectById(id);
            if(alipayMchBatch == null ){
                return;
            }

            AlipayMchAuth alipayMchAuth = alipayMchAuthMapper.get(alipayMchBatch.getAuthPartnerAppId(), alipayMchBatch.getAuthAppId(), alipayMchBatch.getAuthUserId(), alipayMchBatch.getMerId());
            if(alipayMchAuth == null){
                logger.error("---提现支付宝转账(个人)，查询支付结果时，该支付宝授权账号不存在----");
                return;
            }

            if(alipayMchBatch.getStatus().intValue() == AlipayStatusEnum.WAIT_BUYER_PAY.getId().intValue()){ //等待支付状态

                Integer now = DateUtil.getNowTime();
                if(now - alipayMchBatch.getCreateTime().intValue() < 24*3600 ) { //等待时间小于当天之内的订单

                    AlipayFundBatchDetailQueryResponse queryResponse = alipayFundBatchService.query(alipayMchBatch.getOutBatchNo(), alipayMchAuth.getAppAuthToken());

                    if (queryResponse == null) {
                        return;
                    }

                    //查询订单状态:SUCCESS 批次处理全部成功;PART_SUCCESS 批次处理部分成功;FAIL 全部处理失败;DISUSE 批次单据废弃;INVALID 批次单据中明细全部无效
                    String batchStatus = Tools.getStr(queryResponse.getBatchStatus());
                    //处理完成状态才进行分析
                    if (batchStatus.equals("SUCCESS") || batchStatus.equals("PART_SUCCESS") || batchStatus.equals("FAIL") || batchStatus.equals("DISUSE") || batchStatus.equals("INVALID")) {
                        //获取支付明细
                        List<AccDetailModel> accDetailModelList =  queryResponse.getAccDetailList();
                        if(accDetailModelList == null || accDetailModelList.size() == 0 ){
                            logger.error("--查询提现个人转账记录返回结果出现问题，明细为空--,error={}", JSONObject.toJSONString(queryResponse));
                            return;
                        }

                        alipayMchBatch.setBatchStatus(batchStatus);
                        alipayMchBatch.setSuccessAmount(queryResponse.getSuccessAmount());
                        alipayMchBatch.setFailAmount(queryResponse.getFailAmount());
                        alipayMchBatch.setSuccessCount(Tools.getLong(queryResponse.getSuccessCount()).intValue());
                        alipayMchBatch.setFailCount(Tools.getLong(queryResponse.getFailCount()).intValue());
                        alipayMchBatch.setErrorCode(queryResponse.getErrorCode());
                        alipayMchBatch.setFailReason(queryResponse.getFailReason());
                        alipayMchBatch.setStatus(AlipayStatusEnum.TRADE_SUCCESS.getId().intValue()); //支付成功
                        alipayMchBatch.setUpdateTime(now);
                        int i = alipayMchBatchMapper.updateByIdSelective(alipayMchBatch);
                        if(i != 1){
                           logger.error("--修改提现个人支付宝批量转账记录失败--");
                            return;
                        }

                        //修改支付明细
                        for (AccDetailModel accDetailModel : accDetailModelList){
                            //商户明细订单号(提现列表主键id)
                            String outBizNo = accDetailModel.getOutBizNo();
                            //查询数据库中的订单记录
                            AlipayMchBatchDetail alipayMchBatchDetail = alipayMchBatchDetailMapper.selectByOutBatchNoAndOutBizNo(alipayMchBatch.getOutBatchNo(), outBizNo);
                            if(alipayMchBatchDetail != null){
                                alipayMchBatchDetail.setAlipayOrderNo(accDetailModel.getAlipayOrderNo());
                                alipayMchBatchDetail.setDetailId(accDetailModel.getDetailId());
                                //子交易记录状态（INIT：初始；APPLIED：已下单；DEALED：处理中；SUCCESS：处理成功；DISUSE：已废除；FAIL：处理失败；UNKNOWN：未知状态）
                                String status = Tools.getStr(accDetailModel.getStatus());
                                alipayMchBatchDetail.setStatus(status);
                                alipayMchBatchDetail.setErrorCode(accDetailModel.getErrorCode());
                                alipayMchBatchDetail.setErrorMsg(accDetailModel.getErrorMsg());
                                AccPayeeInfo payeeInfo = accDetailModel.getPayeeInfo();
                                if(payeeInfo != null){
                                    alipayMchBatchDetail.setPayeeAccount(payeeInfo.getPayeeAccount());
                                    alipayMchBatchDetail.setPayeeName(payeeInfo.getPayeeName());
                                }
                                alipayMchBatchDetail.setGmtCreate(accDetailModel.getGmtCreate());
                                alipayMchBatchDetail.setGmtFinish(accDetailModel.getGmtFinish());
                                alipayMchBatchDetail.setUpdateTime(now);
                                //修改子交易信息
                                alipayMchBatchDetailMapper.updateByIdSelective(alipayMchBatchDetail);

                                //修改提现记录
                                if(status.equals("SUCCESS")){//提现个人支付宝转账成功
                                    userTakeBalService.updateAlipayMct(Long.valueOf(outBizNo), 1, alipayMchBatch.getMerId());
                                }else{//提现个人支付宝转账失败
                                    userTakeBalService.updateAlipayMct(Long.valueOf(outBizNo), 0, alipayMchBatch.getMerId());
                                }
                            }
                        }

                    }
                }else{
                    //关闭支付宝订单
                    alipayMchBatch.setFailAmount(String.valueOf(alipayMchBatch.getTotalAmount()));
                    alipayMchBatch.setFailCount(Tools.getInteger(alipayMchBatch.getTotalItemCount()));
                    alipayMchBatch.setStatus(AlipayStatusEnum.TRADE_CLOSED.getId());
                    alipayMchBatch.setUpdateTime(now);
                    alipayMchBatch.setErrorCode("TRADE_HAS_CLOSE");
                    alipayMchBatch.setFailReason("超时不支付，系统自动关闭");
                    int i = alipayMchBatchMapper.updateByIdSelective(alipayMchBatch);
                    if(i != 1){
                        throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改支付宝交易记录失败");
                    }

                    //查询该批次支付的所有子订单，将提现状态修改为待处理
                    AlipayMchBatchDetailQuery alipayMchBatchDetailQuery = new AlipayMchBatchDetailQuery();
                    alipayMchBatchDetailQuery.setMerId(alipayMchBatch.getMerId());
                    alipayMchBatchDetailQuery.setOutBatchNo(alipayMchBatch.getOutBatchNo());
                    List<AlipayMchBatchDetail> alipayMchBatchDetailList = alipayMchBatchDetailMapper.findByList(alipayMchBatchDetailQuery);
                    if(alipayMchBatchDetailList != null && alipayMchBatchDetailList.size() > 0){
                        for (AlipayMchBatchDetail alipayMchBatchDetail : alipayMchBatchDetailList){
                            //修改支付明细
                            alipayMchBatchDetail.setStatus(AlipayMchBatchDetailStatusEnum.DISUSE.getKey());//废除
                            alipayMchBatchDetail.setErrorCode("FORCE_DISUSE");
                            alipayMchBatchDetail.setErrorMsg("终止支付，关闭订单");
                            alipayMchBatchDetailMapper.updateByIdSelective(alipayMchBatchDetail);
                            //修改提现记录为待处理
                            userTakeBalService.updateAlipayMct(Long.valueOf(alipayMchBatchDetail.getOutBizNo()), 0, alipayMchBatch.getMerId());
                        }
                    }

                    try{
                        //关闭支付宝交易记录
//                        AlipayTradeCloseRequest request = new AlipayTradeCloseRequest();
//                        JSONObject bizContent = new JSONObject();
//                        bizContent.put("out_trade_no", alipayDetail.getTradeno());
//                        request.setBizContent(bizContent.toString());
//                        AlipayTradeCloseResponse response = alipayClient.certificateExecute(request);
                    }catch (Exception e){

                    }
                }
            }
        }catch (Exception e){
            logger.error("查询个人支付宝转账结果失败,error={}", e.getMessage());
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, e.getMessage());
        }
    }
}
